<template>
	<scroll-view :scroll-y="true" @scrolltolower="scrolltolower" style="width: 100wh;box-sizing: border-box; "
		:style="{height,backgroundColor: bgColor,padding}">
		<view class="scroll-view_H">
			<view v-for="(col, index) in dataArr" :key="index" class="column" :style="{width:rowWidth}">
				<view v-for="(item, i) in col" :key="i" class="scroll-item" @click="clickItem(item)">
					<slot name="scrollItem" :item="item" :index="i"></slot>
				</view>
			</view>
		</view>
		<slot name="bottom"></slot>
	</scroll-view>
</template>

<script>
	export default {
		data() {
			return {
				dataArr: [],
				width: "",
			};
		},
		props: {
			//数据
			data: {
				type: Array,
				required: true
			},
			//自定义key值（已废弃）
			columnKey: {
				type: String,
				default: 'id'
			},
			//列数
			columnCount: {
				type: Number,
				default: 2
			},
			//背景颜色
			bgColor: {
				type: String,
				default: '#eee'
			},
			//容器高度
			height: {
				type: String,
				default: '100vh'
			},
			//内边距
			padding: {
				type: String,
				default: '20rpx'
			},
			//列间距
			gap: {
				type: String,
				default: '10rpx'
			},
		},
		watch: {
			data: {
				immediate: true,
				handler(newList, oldVal) {
					this.handleData(newList)
				},
				deep:true
			}
		},
		computed: {
			columnWidth() {
				return uni.getSystemInfoSync().windowWidth / this.columnCount - this.gap;
			},
			rowWidth() {
				return `calc(100% / ${this.columnCount} -  ${this.gap} )`
			}
		},
		methods: {
			handleData(items) {

				let cols = Array.from({
					length: this.columnCount
				}, () => []);

				items.forEach((item, index) => {
					let shortestCol = cols.reduce((min, col, idx) => (col.length < cols[min].length ? idx : min), 0);
					cols[shortestCol].push(item);
				});
				this.dataArr = cols;
			},
			// 子元素点击事件
			clickItem(item) {
				this.$emit('clickItem', item)
			},
			// 滚动到底部触发
			scrolltolower() {
				this.$emit('scrolltolower', '')
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* #ifdef H5 || MP-WEIXIN */
	// 通过样式穿透，隐藏H5下，scroll-view下的滚动条
	scroll-view ::v-deep ::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}

	/* #endif */
	.scroll-view_H {
		width: 100%;
		display: flex;
		background-color: transparent;
		box-sizing: border-box;
		justify-content: space-between;
	}

	.column {
		width: 100%;
		flex-shrink: 0;

		.scroll-item-box {
			width: 100%;
			height: auto;
			overflow: hidden;
		}
	}

	.scroll-item {
		width: 100%;
		height: auto;
	}
</style>